package com.mystudy.leetcode.problem.tree.p_606;

import com.mystudy.leetcode.base.TreeNode;
import com.mystudy.leetcode.base.TreeNodeUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author 周志龙
 * @Email 15216876513@163.com
 * @Date on 2019/7/25 23:23
 * @Description 根据二叉树创建字符串
 */
public class Solution {
    private static final Logger LOGGER = LoggerFactory.getLogger(Solution.class);

    long startTime = 0L;
    long endTime = 0L;


    @Before
    public void before() {
        startTime = System.nanoTime();
    }

    @Test
    public void test() {
        TreeNode root = TreeNodeUtils.generateTwoTrees(new Integer[]{1, 2, 3, null, 4});
        TreeNodeUtils.show(root);
        String result = tree2str(root);
        LOGGER.debug("result = [{}]", result);
    }

    @After
    public void after() {
        endTime = System.nanoTime();
        double cost = (endTime - startTime) / 1000000.0;
        LOGGER.debug("cost = [{} ms ]", cost);
    }


    public String tree2str(TreeNode t) {
        StringBuilder result = new StringBuilder();
        if (t == null) {
            return "";
        }
        append(t, result);
        return result.toString();
    }

    private void append(TreeNode t, StringBuilder result) {
        if (t == null) {
            return;
        }
        result.append(t.val);
        if (t.left != null) {
            result.append("(");
            append(t.left, result);
            result.append(")");
        } else if (t.right != null) {
            result.append("()");
        }
        if (t.right != null) {
            result.append("(");
            append(t.right, result);
            result.append(")");
        }
    }
}
